import React, { useState } from 'react';
import { 
  Card, 
  Table, 
  Button, 
  Modal, 
  Form, 
  Input, 
  Select, 
  InputNumber, 
  Space, 
  Checkbox, 
  message,
  Row,
  Col,
  Typography,
  Divider,
  Progress,
  Alert
} from 'antd';
import { 
  PlusOutlined, 
  DeleteOutlined, 
  EditOutlined,
  UploadOutlined,
  DownloadOutlined,
  PlayCircleOutlined,
  StopOutlined
} from '@ant-design/icons';
import { useCities, useSimulateDataCollection } from '../hooks/useWeatherQueries';
import axios from 'axios';

const { Option } = Select;
const { TextArea } = Input;
const { Title, Text } = Typography;

interface BatchOperation {
  id: string;
  type: 'create' | 'update' | 'delete' | 'collect';
  name: string;
  description: string;
  cityIds: string[];
  parameters: Record<string, any>;
  status: 'pending' | 'running' | 'completed' | 'failed';
  progress: number;
  createdAt: string;
  completedAt?: string;
  results?: any;
  errors?: string[];
}

interface WeatherDataTemplate {
  cityId: string;
  recordedAt: string;
  source: string;
  metrics: Record<string, number | string>;
}

const BatchOperationsPanel: React.FC = () => {
  const [operations, setOperations] = useState<BatchOperation[]>([]);
  const [selectedRowKeys, setSelectedRowKeys] = useState<string[]>([]);
  const [modalVisible, setModalVisible] = useState(false);
  const [operationType, setOperationType] = useState<'create' | 'update' | 'delete' | 'collect'>('create');
  const [form] = Form.useForm();
  const [batchProgress, setBatchProgress] = useState<{ [key: string]: number }>({});

  const { data: cities = [] } = useCities();
  const simulateDataCollection = useSimulateDataCollection();

  // 模拟已有的批量操作
  React.useEffect(() => {
    const mockOperations: BatchOperation[] = [
      {
        id: '1',
        type: 'collect',
        name: '全城市数据采集',
        description: '对所有活跃城市进行天气数据采集',
        cityIds: ['11111111-1111-1111-1111-111111111111', '22222222-2222-2222-2222-222222222222'],
        parameters: { source: 'BatchCollection' },
        status: 'completed',
        progress: 100,
        createdAt: '2024-01-15T10:00:00Z',
        completedAt: '2024-01-15T10:05:00Z',
        results: { successCount: 2, failedCount: 0 }
      },
      {
        id: '2',
        type: 'create',
        name: '批量创建测试数据',
        description: '为指定城市创建模拟天气数据',
        cityIds: ['33333333-3333-3333-3333-333333333333'],
        parameters: { count: 50, baseTemperature: 25 },
        status: 'running',
        progress: 65,
        createdAt: '2024-01-15T14:30:00Z'
      }
    ];
    setOperations(mockOperations);
  }, []);

  const handleCreateOperation = () => {
    setOperationType('create');
    form.resetFields();
    setModalVisible(true);
  };

  const handleExecuteOperation = async (operation: BatchOperation) => {
    setOperations(prev =>
      prev.map(op =>
        op.id === operation.id
          ? { ...op, status: 'running', progress: 0 }
          : op
      )
    );

    try {
      // 模拟批量操作执行
      for (let i = 0; i <= 100; i += 10) {
        await new Promise(resolve => setTimeout(resolve, 200));
        setBatchProgress(prev => ({ ...prev, [operation.id]: i }));
        setOperations(prev =>
          prev.map(op =>
            op.id === operation.id
              ? { ...op, progress: i }
              : op
          )
        );
      }

      // 执行具体操作
      let results: any = {};
      switch (operation.type) {
        case 'collect':
          results = await simulateDataCollection.mutateAsync({
            baseTemperature: operation.parameters.baseTemperature || 20,
            count: operation.cityIds.length
          });
          break;
        case 'create':
          // 批量创建数据的逻辑
          results = { successCount: operation.cityIds.length, failedCount: 0 };
          break;
        case 'update':
        case 'delete':
          results = { successCount: operation.cityIds.length, failedCount: 0 };
          break;
      }

      setOperations(prev =>
        prev.map(op =>
          op.id === operation.id
            ? { 
                ...op, 
                status: 'completed', 
                progress: 100, 
                completedAt: new Date().toISOString(),
                results 
              }
            : op
        )
      );

      message.success(`批量操作"${operation.name}"执行成功`);
    } catch (error: any) {
      setOperations(prev =>
        prev.map(op =>
          op.id === operation.id
            ? { 
                ...op, 
                status: 'failed', 
                errors: [error.message || '操作失败'] 
              }
            : op
        )
      );
      message.error(`批量操作"${operation.name}"执行失败`);
    }
  };

  const handleStopOperation = (operationId: string) => {
    setOperations(prev =>
      prev.map(op =>
        op.id === operationId
          ? { ...op, status: 'failed', errors: ['用户手动停止'] }
          : op
      )
    );
    message.info('操作已停止');
  };

  const handleDeleteOperation = (operationId: string) => {
    setOperations(prev => prev.filter(op => op.id !== operationId));
    message.success('删除批量操作成功');
  };

  const handleSaveOperation = async (values: any) => {
    try {
      const newOperation: BatchOperation = {
        id: Date.now().toString(),
        type: operationType,
        name: values.name,
        description: values.description || '',
        cityIds: values.cityIds || [],
        parameters: {
          source: values.source || 'BatchOperation',
          baseTemperature: values.baseTemperature,
          count: values.count,
          ...values.additionalParams
        },
        status: 'pending',
        progress: 0,
        createdAt: new Date().toISOString()
      };

      setOperations(prev => [...prev, newOperation]);
      setModalVisible(false);
      form.resetFields();
      message.success('创建批量操作成功');
    } catch (error) {
      message.error('创建批量操作失败');
    }
  };

  const getStatusColor = (status: string) => {
    switch (status) {
      case 'completed': return 'success';
      case 'running': return 'processing';
      case 'failed': return 'error';
      default: return 'default';
    }
  };

  const getStatusText = (status: string) => {
    switch (status) {
      case 'pending': return '等待执行';
      case 'running': return '执行中';
      case 'completed': return '已完成';
      case 'failed': return '执行失败';
      default: return '未知';
    }
  };

  const columns = [
    {
      title: '操作名称',
      dataIndex: 'name',
      key: 'name',
      render: (text: string, record: BatchOperation) => (
        <Space direction="vertical" size="small">
          <Text strong>{text}</Text>
          <Text type="secondary" style={{ fontSize: 12 }}>
            {record.description}
          </Text>
        </Space>
      )
    },
    {
      title: '操作类型',
      dataIndex: 'type',
      key: 'type',
      render: (type: string) => {
        const typeMap = {
          create: '批量创建',
          update: '批量更新',
          delete: '批量删除',
          collect: '数据采集'
        };
        return typeMap[type as keyof typeof typeMap] || type;
      }
    },
    {
      title: '目标城市',
      dataIndex: 'cityIds',
      key: 'cityIds',
      render: (cityIds: string[]) => `${cityIds.length} 个城市`
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (status: string, record: BatchOperation) => (
        <Space direction="vertical" size="small">
          <span style={{ color: getStatusColor(status) }}>
            {getStatusText(status)}
          </span>
          {status === 'running' && (
            <Progress 
              percent={batchProgress[record.id] || record.progress} 
              size="small"
              status="active"
            />
          )}
          {status === 'completed' && record.results && (
            <Text type="success" style={{ fontSize: 11 }}>
              成功: {record.results.successCount} | 失败: {record.results.failedCount}
            </Text>
          )}
          {status === 'failed' && record.errors && (
            <Text type="danger" style={{ fontSize: 11 }}>
              {record.errors[0]}
            </Text>
          )}
        </Space>
      )
    },
    {
      title: '创建时间',
      dataIndex: 'createdAt',
      key: 'createdAt',
      render: (time: string) => new Date(time).toLocaleString()
    },
    {
      title: '操作',
      key: 'actions',
      render: (record: BatchOperation) => (
        <Space>
          {record.status === 'pending' && (
            <Button
              type="primary"
              size="small"
              icon={<PlayCircleOutlined />}
              onClick={() => handleExecuteOperation(record)}
            >
              执行
            </Button>
          )}
          {record.status === 'running' && (
            <Button
              danger
              size="small"
              icon={<StopOutlined />}
              onClick={() => handleStopOperation(record.id)}
            >
              停止
            </Button>
          )}
          {(record.status === 'completed' || record.status === 'failed') && (
            <Button
              danger
              size="small"
              icon={<DeleteOutlined />}
              onClick={() => handleDeleteOperation(record.id)}
            >
              删除
            </Button>
          )}
        </Space>
      )
    }
  ];

  const renderOperationForm = () => {
    switch (operationType) {
      case 'create':
        return (
          <>
            <Form.Item
              name="baseTemperature"
              label="基础温度"
              rules={[{ required: true, message: '请输入基础温度' }]}
            >
              <InputNumber
                style={{ width: '100%' }}
                placeholder="输入基础温度"
                suffix="°C"
                step={0.1}
              />
            </Form.Item>
            <Form.Item
              name="count"
              label="每个城市生成数据条数"
              rules={[{ required: true, message: '请输入生成数据条数' }]}
            >
              <InputNumber
                style={{ width: '100%' }}
                placeholder="输入数据条数"
                min={1}
                max={1000}
              />
            </Form.Item>
          </>
        );
      case 'collect':
        return (
          <Form.Item
            name="source"
            label="数据源标识"
          >
            <Input placeholder="输入数据源标识（可选）" />
          </Form.Item>
        );
      case 'update':
        return (
          <Form.Item
            name="updateFields"
            label="更新字段"
          >
            <TextArea
              rows={4}
              placeholder="输入要更新的字段JSON格式，例如：&#10;{&#10;  &quot;source&quot;: &quot;UpdatedSource&quot;,&#10;  &quot;temperature&quot;: 25.5&#10;}"
            />
          </Form.Item>
        );
      default:
        return null;
    }
  };

  return (
    <div>
      <Row gutter={16} style={{ marginBottom: 16 }}>
        <Col span={24}>
          <Alert
            message="批量操作提示"
            description="批量操作会影响大量数据，请谨慎使用。建议在低峰期执行大批量操作。"
            type="info"
            showIcon
            style={{ marginBottom: 16 }}
          />
        </Col>
      </Row>

      <Card
        title="批量操作管理"
        extra={
          <Space>
            <Button
              type="primary"
              icon={<PlusOutlined />}
              onClick={handleCreateOperation}
            >
              创建批量操作
            </Button>
          </Space>
        }
      >
        <Table
          columns={columns}
          dataSource={operations}
          rowKey="id"
          pagination={{ pageSize: 10 }}
          rowSelection={{
            selectedRowKeys,
            onChange: setSelectedRowKeys,
            getCheckboxProps: (record) => ({
              disabled: record.status === 'running'
            })
          }}
        />

        {selectedRowKeys.length > 0 && (
          <div style={{ marginTop: 16, padding: 16, background: '#f0f2f5', borderRadius: 6 }}>
            <Space>
              <Text>已选择 {selectedRowKeys.length} 个操作</Text>
              <Button
                size="small"
                onClick={() => {
                  const pendingOps = operations.filter(op => 
                    selectedRowKeys.includes(op.id) && op.status === 'pending'
                  );
                  pendingOps.forEach(op => handleExecuteOperation(op));
                }}
                disabled={!operations.some(op => 
                  selectedRowKeys.includes(op.id) && op.status === 'pending'
                )}
              >
                批量执行
              </Button>
              <Button
                danger
                size="small"
                onClick={() => {
                  const completedOps = operations.filter(op => 
                    selectedRowKeys.includes(op.id) && 
                    (op.status === 'completed' || op.status === 'failed')
                  );
                  completedOps.forEach(op => handleDeleteOperation(op.id));
                  setSelectedRowKeys([]);
                }}
                disabled={!operations.some(op => 
                  selectedRowKeys.includes(op.id) && 
                  (op.status === 'completed' || op.status === 'failed')
                )}
              >
                批量删除
              </Button>
            </Space>
          </div>
        )}
      </Card>

      <Modal
        title="创建批量操作"
        open={modalVisible}
        onCancel={() => setModalVisible(false)}
        width={600}
        footer={null}
      >
        <Form
          form={form}
          layout="vertical"
          onFinish={handleSaveOperation}
        >
          <Form.Item
            name="type"
            label="操作类型"
            rules={[{ required: true, message: '请选择操作类型' }]}
          >
            <Select 
              placeholder="选择操作类型"
              onChange={setOperationType}
            >
              <Option value="create">批量创建数据</Option>
              <Option value="collect">批量数据采集</Option>
              <Option value="update">批量更新数据</Option>
              <Option value="delete">批量删除数据</Option>
            </Select>
          </Form.Item>

          <Form.Item
            name="name"
            label="操作名称"
            rules={[{ required: true, message: '请输入操作名称' }]}
          >
            <Input placeholder="输入批量操作名称" />
          </Form.Item>

          <Form.Item name="description" label="操作描述">
            <TextArea
              rows={2}
              placeholder="输入操作描述（可选）"
            />
          </Form.Item>

          <Form.Item
            name="cityIds"
            label="目标城市"
            rules={[{ required: true, message: '请选择至少一个城市' }]}
          >
            <Select
              mode="multiple"
              placeholder="选择目标城市"
              style={{ width: '100%' }}
              options={cities.map((city: any) => ({
                label: `${city.name} (${city.country})`,
                value: city.id
              }))}
            />
          </Form.Item>

          <Divider>操作参数</Divider>

          {renderOperationForm()}

          <Form.Item style={{ marginBottom: 0, textAlign: 'right', marginTop: 24 }}>
            <Space>
              <Button onClick={() => setModalVisible(false)}>
                取消
              </Button>
              <Button type="primary" htmlType="submit">
                创建操作
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default BatchOperationsPanel;